package com.yilian.xlmusic.android.utils.music;

import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;

import com.yilian.xlmusic.android.base.MyApplication;

import java.io.IOException;

public class MediaUtil {
    private static final String TAG = "MediaUtil";
    private MediaPlayer player;
    private EventListener eventListener;

    private MediaUtil() {
        player = new MediaPlayer();
    }

    private static MediaUtil instance = new MediaUtil();

    public static MediaUtil getInstance() {
        return instance;
    }

    public MediaPlayer getPlayer() {
        return player;
    }

    public static String MediaUrl;

    public void setEventListener(final EventListener eventListener) {
        if (player != null) {
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {

                    eventListener.onCompolete();
                }
            });
        }
        this.eventListener = eventListener;
    }
//    public void setEventListener(final EventListener eventListener,ChangeItem changeItem) {
//        if (player != null){
//            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//                @Override
//                public void onCompletion(MediaPlayer mp) {
//                    eventListener.onStop();
//                    eventListener.onStopMusic(changeItem);
//                }
//            });
//        }
//        this.eventListener = eventListener;
//    }


    public void play(String music_url) {
        MediaUrl = music_url;
        try {
            if (eventListener != null) {
                eventListener.onStop();
            }
            player.reset();
            player.setDataSource(music_url);
            player.prepare();
            player.start();
        } catch (IOException e) {
            Log.e(TAG, "play error:" + e);
        }
    }


    public void rePlay() {
        player.start();
    }

    public void stop() {
        if (player != null && player.isPlaying()) {
            player.stop();
            player.release();
        }
    }


    public void pause() {
        if (player != null && player.isPlaying()) {
            player.pause();
        }
    }

    public boolean isPlaying() {
        if (player != null) {
            return player.isPlaying();
        }
        return false;
    }

    public long getDuration(String path) {
        player = MediaPlayer.create(MyApplication.getContext(), Uri.parse(path));
        return player.getDuration();
    }

    /**
     * 播放器事件监听
     */
    public interface EventListener {
        void onStop();

        void onCompolete();

    }
}
